package com.mes.web.controller.hy;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.mes.entity.cb.Materiel;
import com.mes.entity.hy.Maters;
import com.mes.entity.jy.DaysheduDetail;
import com.mes.entity.lc.MaterialStock;
import com.mes.entity.lz.BOM;
import com.mes.entity.tdd.Staff;
import com.mes.entity.zc.MaterNum;
import com.mes.service.hy.IMaterService;
import com.mes.service.tdd.StaffService;
import com.mes.utils.DateJsonValueProcessor;
import com.mes.utils.ResponseUtil;
import com.mes.utils.StringUtil;

/**
 * 
 * @ClassName:MaterController
 * @Description: 领料管理controller
 * @Author hy
 * @Date 2018-5-30下午2:16:15
 * @version 1.0
 */
@Controller
@RequestMapping("/mater")
public class MaterController {

	@Resource
	private IMaterService iMaterService;

	@Resource
	private StaffService staffService;

	MaterialStock materialStock = null;
	List<BOM> bomList = new ArrayList<>();
	Maters maters1 = new Maters();
	Maters maters = new Maters();

	/**
	 * 审批
	 * 
	 * @param response
	 * @param request
	 * @param pickOdd
	 *            领料单号
	 * @throws Exception
	 */
	@RequestMapping("/approval")
	public void approval(HttpServletResponse response,
			HttpServletRequest request, String pickOdd) throws Exception {
		Maters maters2 = iMaterService.selestByPickOdd(pickOdd);
		int flag = 0;
		HttpSession session = request.getSession();
		// 从session中取出用户身份信息
		Staff userSession = (Staff) session.getAttribute("staff");
		if (userSession != null) {
			maters2.setAuditor(userSession.getStaffname());
		}
		// 2为审批，1为未审批
		maters2.setRemark1("2");
		flag = iMaterService.updMa(maters2);
		ResponseUtil.write(response, flag);
	}

	/**
	 * 撤销审批
	 * 
	 * @param response
	 * @param request
	 * @param pickOdd
	 *            领料单号
	 * @throws Exception
	 */
	@RequestMapping("/calApp")
	public void calApp(HttpServletResponse response,
			HttpServletRequest request, String pickOdd) throws Exception {
		Maters maters2 = iMaterService.selestByPickOdd(pickOdd);
		int flag = 0;
		// 清除审批人
		maters2.setAuditor("");
		// 将状态改为1
		maters2.setRemark1("1");
		flag = iMaterService.updMa(maters2);
		ResponseUtil.write(response, flag);
	}

	/**
	 * 查询领料人
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/selName")
	public void selName(HttpServletResponse response) throws Exception {
		List<Staff> stList = staffService.selName();
		JSONArray jsonArray = JSONArray.fromObject(stList);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 查询所有
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("selectAll")
	public void selectAll(HttpServletResponse response) throws Exception {
		List<Maters> materList = iMaterService.selectAll();
		int total = iMaterService.selectCountMT();

		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(materList, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("total", total);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 分页查询
	 * 
	 * @param response
	 * @param request
	 * @param limit
	 *            每页显示的行数
	 * @param offset
	 *            页码
	 * @param maters
	 *            领料实体类
	 * @throws Exception
	 */
	@RequestMapping("/select")
	public void select(HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam(value = "limit", required = false) String limit,
			@RequestParam(value = "offset", required = false) String offset,
			Maters maters) throws Exception {
		if (!"".equals(offset)) {
			maters.setPage(Integer.parseInt(offset) / Integer.parseInt(limit));
		}
		maters.setPageSize(Integer.parseInt(limit));
		// 用于导出当前页
		maters1.setPage(maters.getPage());
		maters1.setPageSize(maters.getPageSize());

		int total = iMaterService.selectCountMT();
		List<Maters> materList = iMaterService.select(maters);
		// 判断是否空白页
		if (materList.size() == 0) {
			maters.setPage(maters.getPage() - 1);
			materList = iMaterService.select(maters);
		}

		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(materList, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("total", total);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 时间段查询
	 * 
	 * @param response
	 * @param request
	 * @param limit
	 *            每页显示的行数
	 * @param offset
	 *            页码
	 * @param maters
	 *            领料实体类
	 * @throws Exception
	 */
	@RequestMapping("/selectByTime")
	public void selectByTime(HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam(value = "limit", required = false) String limit,
			@RequestParam(value = "offset", required = false) String offset,
			Maters maters) throws Exception {
		if (!"".equals(offset)) {
			maters.setPage(Integer.parseInt(offset) / Integer.parseInt(limit));
		}
		maters.setPageSize(Integer.parseInt(limit));

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (maters.getEndDate() != null && !"".equals(maters.getEndDate())) {
			maters.setEndDate(sdf.format(sdf.parse(maters.getEndDate())));
		}
		if (maters.getStartDate() != null
				&& !("").equals(maters.getStartDate())) {
			maters.setStartDate(sdf.format(sdf.parse(maters.getStartDate())));
		}

		List<Maters> materList = iMaterService.selectByTime(maters);
		int total = iMaterService.selectCount(maters);

		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(materList, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("total", total);
		jsonObject.put("rows", jsonArray);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 查询领料单号，为了新增领料单号自增1所用
	 * 
	 * @param request
	 * @param model
	 *            数据模型
	 * @return 得到领料单号返回指定前台页面
	 */
	@RequestMapping("/selectOdd")
	public String selectOdd(HttpServletRequest request, Model model) {
		String a;
		if (iMaterService.selectOdd() == null
				|| ("").equals(iMaterService.selectOdd())) {
			a = "领料单号1";
		} else {
			a = (iMaterService.selectOdd().substring(0, 4) + ((Integer
					.parseInt(iMaterService.selectOdd().substring(4))) + 1))
					.toString();
		}
		model.addAttribute("odd", a);
		return "hy/addLingliao";
	}

	/**
	 * 新增
	 * 
	 * @param response
	 * @param request
	 * @param maters
	 *            领料实体类
	 * @param id
	 *            排产带id
	 * @throws Exception
	 */
	@RequestMapping("/insert")
	public void insert(HttpServletResponse response,
			HttpServletRequest request, Maters maters, String id)
			throws Exception {
		int flag = 0;
		// 排产单详情类
		DaysheduDetail day = new DaysheduDetail();
		// 为1时未提交审核，2已提交审核，3审核通过，其他审核失败
		maters.setRemark1("1");
		// 为1时未领料
		maters.setRemark2("1");
		// 将排产单和领料单绑定
		maters.setRemark3(id.substring(0, id.length() - 1));
		flag = iMaterService.insert(maters);
		// 修改排产单领料状态，根据id去jy_pcdetail表中查询排产单
		String[] ids = id.split(",");
		for (int i = 0; i < ids.length; i++) {
			day.setId(Long.parseLong(ids[i]));
			// 修改排产单状态
			day.setRemark9("已领料");
			iMaterService.setRe9(day);
		}
		ResponseUtil.write(response, flag);
	}

	/**
	 * 删除，可批量删除，如果选中删除有已审核的领料单，删除失败，跳出删除
	 * 
	 * @param response
	 * @param pickOdd
	 *            领料单id字符串
	 * @throws Exception
	 */
	@RequestMapping("/delete")
	public void delete(HttpServletResponse response, String pickOdd)
			throws Exception {
		DaysheduDetail day = new DaysheduDetail();
		String[] pickOddsStrings = pickOdd.split(",");
		int total = 0;
		List<Maters> mList = new ArrayList<>();
		for (int i = 0; i < pickOddsStrings.length; i++) {
			maters1 = iMaterService.selestByPickOdd(pickOddsStrings[i]);
			mList.add(maters1);
		}
		int flag = 0;
		for (int i = 0; i < mList.size(); i++) {
			// 如果已审核flag+1
			if (!"1".equals(mList.get(i).getRemark1())) {
				flag += 1;
			}
		}
		// 没有已审核的进入删除
		if (flag == 0) {
			for (int i = 0; i < mList.size(); i++) {
				// 根据mater表中remark3查询jy-detail表，将remark9修改为null
				// 获取排产单id的值
				String id = mList.get(i).getRemark3();
				if (id != null && !"".equals(id)) {
					String[] ids = id.split(",");
					for (int j = 0; j < ids.length; j++) {
						// 将id放入类中
						day.setId(Long.valueOf(ids[j]));
						// 将空值放入类中
						day.setRemark9("");
						// 根据这个类去修改排产单，删除排产单和领料单的关联
						iMaterService.update(day);
					}
				}
				// 删除该领料单的领料详情
				iMaterService.delBom(pickOddsStrings[i]);

				total += iMaterService.delete(pickOddsStrings[i]);
			}
		} else {
			total = -1;
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("success", total);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 导出当前页领料单
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/export")
	public void export(HttpServletResponse response) throws Exception {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("当前页领料单");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("序号");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("领料单号");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("领料时间");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("领料人");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("审核人");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("审核状态");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("领料状态");
		cell.setCellStyle(style);
		// 导出当前页
		List<Maters> list = iMaterService.select(maters1);
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow((int) i + 1);
			Maters maters2 = list.get(i);
			row.createCell(0).setCellValue(i + 1);
			row.createCell(1).setCellValue(maters2.getPickOdd());
			row.createCell(2).setCellValue(maters2.getPickDate());
			row.createCell(3).setCellValue(maters2.getPickMan());
			row.createCell(4).setCellValue(maters2.getAuditor());
			row.createCell(5).setCellValue(maters2.getRemark1());
			row.createCell(6).setCellValue(maters2.getRemark2());
		}
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowtime = sdf.format(now);
		String fileName = nowtime + "领料单.xls";
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
					output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导出领料单明细
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/exportDetail")
	public void exportDet(HttpServletResponse response) throws Exception {
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("领料单明细");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("领料单号");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("领料时间");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("领料人");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("审核人");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("审核状态");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("领料状态");
		cell.setCellStyle(style);
		// 导出一行所选中的领料单号信息（根据领料单号查找该条信息）
		Maters maters2 = iMaterService.selestByPickOdd(bomList.get(0)
				.getRemark02());
		row = sheet.createRow(1);
		row.createCell(0).setCellValue(maters2.getPickOdd());
		row.createCell(1).setCellValue(maters2.getPickDate());
		row.createCell(2).setCellValue(maters2.getPickMan());
		row.createCell(3).setCellValue(maters2.getAuditor());
		String sma = "1";
		String nor = "2";
		String big = "3";
		if (sma.equals(maters2.getRemark1())) {
			row.createCell(4).setCellValue("未提交审核");
		} else if (nor.equals(maters2.getRemark1())) {
			row.createCell(4).setCellValue("已提交审核");
		} else if (big.equals(maters2.getRemark1())) {
			row.createCell(4).setCellValue("审核通过");
		} else {
			row.createCell(4).setCellValue("审核失败");
		}
		if (sma.equals(maters2.getRemark2())) {
			row.createCell(5).setCellValue("未领料");
		} else {
			row.createCell(5).setCellValue("已领料");
		}
		row = sheet.createRow(4);
		cell = row.createCell(0);
		cell.setCellValue("序号");
		cell.setCellStyle(style);
		cell = row.createCell(1);
		cell.setCellValue("物料名称");
		cell.setCellStyle(style);
		cell = row.createCell(2);
		cell.setCellValue("型号");
		cell.setCellStyle(style);
		cell = row.createCell(3);
		cell.setCellValue("计量单位");
		cell.setCellStyle(style);
		cell = row.createCell(4);
		cell.setCellValue("需求数量");
		cell.setCellStyle(style);
		cell = row.createCell(5);
		cell.setCellValue("线边库库存");
		cell.setCellStyle(style);
		cell = row.createCell(6);
		cell.setCellValue("最高安全库存");
		cell.setCellStyle(style);
		cell = row.createCell(7);
		cell.setCellValue("最低安全库存");
		cell.setCellStyle(style);
		cell = row.createCell(8);
		cell.setCellValue("应领料量");
		cell.setCellStyle(style);
		// 领料单详情
		List<BOM> list1 = iMaterService.selectDetail(bomList.get(0));
		for (int i = 0; i < list1.size(); i++) {
			row = sheet.createRow((int) i + 5);
			BOM bom1 = list1.get(i);
			row.createCell(0).setCellValue(i + 1);
			row.createCell(1).setCellValue(bom1.getMaterialName());
			row.createCell(2).setCellValue(bom1.getRemark01());
			row.createCell(3).setCellValue(bom1.getMaterialUnit());
			row.createCell(4).setCellValue(bom1.getLingliaoRequireCount());
			row.createCell(5).setCellValue(bom1.getXianbianCount());
			row.createCell(6).setCellValue(bom1.getRemark03());
			row.createCell(7).setCellValue(bom1.getRemark04());
			row.createCell(8).setCellValue(bom1.getLingliaoRequireCount());
		}
		Date now = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowtime = sdf.format(now);
		String fileName = nowtime + "领料单.xls";
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
					output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查询排产单
	 * 
	 * @param response
	 * @param limit
	 *            每页显示行数
	 * @param offset
	 *            页码
	 * @param daysheduDetail
	 *            排产单详情实体类
	 * @throws Exception
	 */
	@RequestMapping("/selectDetail")
	public void selectDetail(HttpServletResponse response,
			@RequestParam(value = "limit", required = false) String limit,
			@RequestParam(value = "offset", required = false) String offset,
			DaysheduDetail daysheduDetail) throws Exception {
		if (!"".equals(offset)) {
			daysheduDetail.setPage(Integer.parseInt(offset)
					/ Integer.parseInt(limit));
		}
		daysheduDetail.setPageSize(Integer.parseInt(limit));

		Date day = new Date();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		// 判断传进来的查询时间是否为空，为空默认为当前时间
		if (daysheduDetail.getEndtime().equals(null)
				|| ("").equals(daysheduDetail.getEndtime())) {
			daysheduDetail.setEndtime(df.format(day));
		}

		List<DaysheduDetail> dayList = iMaterService.selectDay(daysheduDetail);
		int total = iMaterService.selectDayCount(daysheduDetail);

		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.registerJsonValueProcessor(java.util.Date.class,
				new DateJsonValueProcessor("yyyy-MM-dd"));
		JSONArray jsonArray = JSONArray.fromObject(dayList, jsonConfig);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("rows", jsonArray);
		jsonObject.put("total", total);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 查询明细
	 * 
	 * @param response
	 * @param limit
	 *            每页显示行数
	 * @param offset
	 *            页码
	 * @param bom
	 *            领料明细实体类
	 * @throws Exception
	 */
	@RequestMapping("/selectDet")
	public void selectDet(HttpServletResponse response,
			@RequestParam(value = "limit", required = false) String limit,
			@RequestParam(value = "offset", required = false) String offset,
			BOM bom) throws Exception {
		// 转码
		if (bom.getRemark02() != null
				&& bom.getRemark02().equals(
						new String(bom.getRemark02().getBytes("iso-8859-1"),
								"utf-8"))) {
			bom.setRemark02(new String(
					bom.getRemark02().getBytes("iso-8859-1"), "utf-8"));
		}

		if (!"".equals(offset)) {
			bom.setPage(Integer.parseInt(offset) / Integer.parseInt(limit));
		}
		bom.setPageSize(Integer.parseInt(limit));

		bomList = iMaterService.selectDetail(bom);
		int total = iMaterService.selectDetailCount(bom);

		JSONArray jsonArray = JSONArray.fromObject(bomList);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("rows", jsonArray);
		jsonObject.put("total", total);
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 生成领料单
	 * 
	 * @param pNummArr
	 *            品编
	 * @param lingliaoOrdNum
	 *            领料单号
	 * @param plannum
	 *            生产数量
	 * @param id
	 *            排产单号
	 * @param response
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping("/bom")
	public void bom(@RequestParam(value = "pNummArr[]") String[] pNummArr,
			String lingliaoOrdNum, String plannum,
			HttpServletResponse response, HttpServletRequest request)
			throws Exception {
		List<BOM> bomList1 = new ArrayList<>();
		List<MaterNum> maList = new ArrayList<>();
		Materiel mat = new Materiel();
		// 根据领料单查bom是否有绑定关系，如果有直接删除
		bomList1 = iMaterService.queryBOMInfo(lingliaoOrdNum);
		if (bomList1.size() > 0) {
			iMaterService.delBom(lingliaoOrdNum);
			bomList1 = iMaterService.queryBOMInfo(lingliaoOrdNum);
		}
		// 选择排产单进入
		if (pNummArr.length > 0) {
			for (int i = 0; i < pNummArr.length; i++) {
				// 根据产品去关联表查询所需的物料（拿出一个产品去查关联物料，结果是个集合）
				maList = iMaterService.selMa(pNummArr[i]);
				for (int j = 0; j < maList.size(); j++) {
					BOM bom = new BOM();
					// 根据物料id去cb物料表中查询物料基础信息，是一个类
					mat = iMaterService.queryMaterial(maList.get(j)
							.getMaterid());
					BOM bom2 = new BOM();
					bom2 = iMaterService.selByID(maList.get(j).getMaterid(),
							lingliaoOrdNum);
					if (mat != null) {
						// 根据这条数据计算出的需求数量
						int count = (maList.get(j).getMaternum())
								* (Integer.parseInt(plannum));
						// 如果该物料已存在bom计算表中，提出数字进行累加，如果不存在直接添加
						if (bom2 != null) {
							int xbk = Integer.parseInt(bom2.getXianbianCount());
							// 之前存在的需求数量
							int reCount = Integer.parseInt(bom2
									.getRequireCount());
							/* 将需求量累加后写入BOM类中的RequireCount字段 */
							bom2.setRequireCount(String
									.valueOf(reCount + count));
							/* 将实际领料量累加后写入BOM类中的LingliaoRequireCount字段 */
							bom2.setLingliaoRequireCount(String.valueOf(reCount
									+ count - xbk));
							iMaterService.updateBom(bom2);
							bom2 = null;
						} else {
							// 将物料id放入remark03字段
							bom.setRemark05(String.valueOf(mat.getId()));
							/* 将物料名称写入BOM类中的MaterialName字段 */
							bom.setMaterialName(mat.getName());
							/* 将物料型号写入BOM类中的remark01字段 */
							bom.setRemark01(mat.getMaterialmodel());
							/* 将物料计量单位写入BOM类中的MaterialUnit字段 */
							bom.setMaterialUnit(mat.getCompany());
							/* 将需求量写入BOM类中的RequireCount字段 */
							bom.setRequireCount(String.valueOf(count));
							/* 将最高安全库存写入BOM类中的remark03字段 */
							bom.setRemark03(mat.getRemark8());
							/* 将最底安全库存写入BOM类中的remark04字段 */
							bom.setRemark04(mat.getRemark7());
							/* 将线边库库存写入BOM类中的XianbianCount字段 */
							String nowma = iMaterService.queryJYnowma(String
									.valueOf(mat.getId()));
							if (StringUtil.isNotEmpty(nowma)) {
								bom.setXianbianCount(nowma);
							} else {
								bom.setXianbianCount("0");
							}
							// 将实际领料量写入BOM类中的LingliaoRequireCount字段
							// int类型的需求量，线边库
							int plnum = 0, noma = 0;
							if (bom.getRequireCount() != null
									&& !("").equals(bom.getRequireCount())) {
								plnum = Integer.parseInt(bom.getRequireCount());
							}
							if (nowma != null && !("").equals(nowma)) {
								noma = Integer.parseInt(nowma);
							}
							// 领料数量
							int llc = plnum - noma;
							if (llc <= 0) {
								bom.setLingliaoRequireCount("0");
							} else {
								bom.setLingliaoRequireCount(String.valueOf(llc));
							}
							// 将领料单号和BOM绑定
							if (StringUtil.isNotEmpty(lingliaoOrdNum)) {
								bom.setRemark02(lingliaoOrdNum);
							} else {
								bom.setRemark02(null);
							}
							iMaterService.insertBOM(bom);
							bom = null;
						}
					} else {
						response.getWriter().print(0);
						return;
					}
				}
			}
			response.getWriter().print(1);
		} else {
			response.getWriter().print(0);
		}
	}

	/**
	 * 根据领料单号查询当前的BOM
	 * 
	 * @param response
	 * @param request
	 * @param lingliaoOrder
	 *            领料单号
	 * @throws Exception
	 */
	@RequestMapping("/queryBOMInfo")
	public void queryBOMInfo(HttpServletResponse response,
			HttpServletRequest request, String lingliaoOrder) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset = UTF-8");
		response.setCharacterEncoding("UTF-8");
		if (lingliaoOrder != null
				&& lingliaoOrder.equals(new String(lingliaoOrder
						.getBytes("iso-8859-1"), "utf-8"))) {
			lingliaoOrder = (new String(lingliaoOrder.getBytes("iso-8859-1"),
					"utf-8"));
		}
		List<BOM> bomList1 = iMaterService.queryBOMInfo(lingliaoOrder);
		JSONArray jsonArray = JSONArray.fromObject(bomList1);
		JSONObject config = new JSONObject();
		config.put("rows", jsonArray);
		config.put("total", 10);
		ResponseUtil.write(response, config);
	}

	/* pda接口 */
	/**
	 * 查询所有领料单
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("selMaters")
	public void selMaters(HttpServletResponse response) throws Exception {
		response.setContentType("application/json; charset = utf-8");
		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
		List<Maters> list = iMaterService.selMaters();
		if (list.size() > 0) {
			// 传递数据到页面
			jsonObject.put("code", "200");
			jsonObject.put("message", "");
			jsonObject.put("results", list);
		} else {
			jsonObject.put("code", "500");
			jsonObject.put("message", "查询数据为空");
			jsonObject.put("results", null);
		}
		ResponseUtil.write(response, jsonObject);
	}

	/**
	 * 查询领料单详情
	 * 
	 * @param response
	 * @param lingliaoOrder
	 *            领料单号
	 * @throws Exception
	 */
	@RequestMapping("selDetail")
	public void selDetail(HttpServletResponse response, String lingliaoOrder)
			throws Exception {
		response.setContentType("application/json; charset = utf-8");
		net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
		List<BOM> list = iMaterService.queryBOMInfo(lingliaoOrder);
		
		Iterator<BOM> it = list.iterator(); 
		while(it.hasNext()){ 
			 BOM next = it.next();
			 Integer num =  Integer.parseInt(next.getLingliaoRequireCount());
			
			if( num == 0) {
				it.remove(); 
			}
		} 
		
		if (list.size() > 0) {
			// 传递数据到页面
			jsonObject.put("code", "200");
			jsonObject.put("message", "");
			jsonObject.put("results", list);
		} else {
			jsonObject.put("code", "500");
			jsonObject.put("message", "查询数据为空");
			jsonObject.put("results", null);
		}
		ResponseUtil.write(response, jsonObject);
	}
}
